package com.ly.gen.config;

import com.ly.gen.service.ConnsService;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * //TODO
 *
 * @author leiyuan
 * @date 2023/2/21 0021
 **/
@Component
public class JdbcTemplateContext {

    @Autowired
    private ConnsService connsService;

    public static final Map<Integer, NamedParameterJdbcTemplate> dataSourceMap = new ConcurrentHashMap<>();

    public NamedParameterJdbcTemplate getJdbcTemplate(Integer connId) {
        Map<String, Object> conn = connsService.getConn(connId);
        String dbType = conn.get("db_type").toString();
        if (dataSourceMap.get(dbType) != null) {
            return dataSourceMap.get(dbType);
        }
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(conn.get("conn_addr").toString());
        config.setUsername(conn.get("user_name").toString());
        config.setPassword(conn.get("password").toString());
        NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(new HikariDataSource(config));
        dataSourceMap.put(connId, jdbcTemplate);
        return jdbcTemplate;
    }
}
